package com.wn.pettyloan.security.emp;

import com.wn.pettyloan.entity.Emp;
import com.wn.pettyloan.service.EmpService;
import com.wn.pettyloan.service.MenuService;
import com.wn.pettyloan.service.UserService;
import com.wn.pettyloan.vo.PermissionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: pettyloan
 * @ClassName EmpDetailsServiceImpl
 * @description:
 * @author: 韩旭
 * @create: 2022-12-15 15:28
 **/
@Service
@Slf4j
public class EmpDetailsServiceImpl  implements UserDetailsService {
    @Autowired
    private EmpService empService;
    @Autowired
    private MenuService menuService;
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询出用户实体对象
        Emp emp = empService.selectByUacc(username);
        // 若没查询到一定要抛出该异常，这样才能被Spring Security的错误处理器处理
        if (emp == null) {
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        // 走到这代表查询到了实体对象，那就返回我们自定义的UserDetail对象
        List<PermissionVo> menuList = menuService.selectMenuList(username, 0);
        List<String> permissionlist = menuService.selectPermissionByEmpuacc(username);


        LoginEmp loginEmp = new LoginEmp();
        loginEmp.setEmp(emp);
        loginEmp.setMenuList(menuList);
        loginEmp.setPermissions(permissionlist);
        return loginEmp;
    }
}